/*
 * Copyright (C) 2012 Stephane Ribas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ribas.stephane;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.ribas.stephane.db.DatabaseHelper;

/**
 * This is the activity for feature 3 in the original dashboard application.
 * It displays some text and provides a way to get back to the home activity.
 *
 */

public class RemedesActivity extends ListActivity 
{
	// variable pour le debug ;-)
	private static final String TAG = "StatusActivity";
	
	//MENU OPTIONS
	// Button QUIT + SETTINGS
	final private static int optionGroupId = 1;
	final private static int optionAffectionsItemId = 1;
	final private static int optionAffectionsOrder = 1;
	
	
	// BDD declaration
	protected EditText searchText;
	protected SQLiteDatabase db;
	protected Cursor cursor;
	protected ListAdapter adapter;
	protected ListView remedesList;
	
	// START
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remedeslist);
        db = (new DatabaseHelper(this)).getWritableDatabase();
        searchText = (EditText) findViewById (R.id.searchText);
        fillListView();   
    }
    
    @Override
    public void onListItemClick(ListView parent, View view, int position, long id) {
     	Log.d(TAG, "LIST CLICK");
     	Intent intent = new Intent(this, RemedesDetailsActivity.class);
     	Cursor cursor = (Cursor) adapter.getItem(position);
     	intent.putExtra("NOM_ID", cursor.getInt(cursor.getColumnIndex("_id")));
     	startActivity(intent);
     }
    
	public void onClickSearch(View view) {
    	// || is the concatenation operation in SQLite
		cursor = db.rawQuery("SELECT _id, Nom, Actif, Indication FROM listeremedes WHERE Nom || ' ' || Actif || ' ' || Indication LIKE ?", 
						new String[]{"%" + searchText.getText().toString() + "%"});
		adapter = new SimpleCursorAdapter(
				this, 
				R.layout.activity_remedeslist_item, 
				cursor, 
				new String[] {"Nom", "Actif"}, 
				new int[] {R.id.Nom, R.id.Actif});
		setListAdapter(adapter);
    }
	
    // fillView with list of affection by alphabetic order
	public void fillListView() {
		cursor = db.rawQuery("SELECT _id, Nom, Actif FROM listeremedes WHERE Nom = Nom ORDER By Nom", null);
		adapter = new SimpleCursorAdapter(
				this, 
				R.layout.activity_remedeslist_item, 
				cursor, 
				new String[] {"Nom", "Actif"}, 
				new int[] {R.id.Nom, R.id.Actif});
		setListAdapter(adapter);
    }
    
    //
    // CLOSE la BDD en quittant l'application
    //
   public void onStop(Bundle savedInstanceState) {
    	Log.d(TAG, "QUIT via onStop");
    	db.close();
	}

	/**
	 */
	// Click Methods

	/**
	 * Handle the click on the home button.
	 * 
	 * @param v View
	 * @return void
	 */

	public void onClickHome (View v)
	{
	    goHome (this);
	}


	/**
	 * Handle the click on the HELP button.
	 * 
	 * @param v View
	 * @return void
	 */

	public void onClickHelp (View v)
	{
	    startActivity (new Intent(getApplicationContext(), HelpActivity.class));
	}
	/**
	 * Handle the click on the About button.
	 * 
	 * @param v View
	 * @return void
	 */

	public void onClickAbout (View v)
	{
	    startActivity (new Intent(getApplicationContext(), AboutActivity.class));
	}

	/**
	 * Handle the click on the Quit button.
	 * 
	 * @param v View
	 * @return void
	 */

	public void onClickQuit (View v)
	{
		finish();
	}
	
	/**
	 * onDestroy
	 * The final call you receive before your activity is destroyed. 
	 * This can happen either because the activity is finishing (someone called finish() on it, 
	 * or because the system is temporarily destroying this instance of the activity to save space. 
	 * You can distinguish between these two scenarios with the isFinishing() method.
	 *
	 */


	protected void onDestroy ()
	{
        Log.d(TAG, "Destroy");
        if (db != null) db.close();
		super.onDestroy ();
	}

	/**
	 * Go back to the home activity.
	 * 
	 * @param context Context
	 * @return void
	 */

	public void goHome(Context context) 
	{
	    final Intent intent = new Intent(context, HomeoGratuitHomeActivity.class);
	    intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    context.startActivity (intent);
	}

	/**
	 * Use the activity label to set the text in the activity's title text view.
	 * The argument gives the name of the view.
	 *
	 * <p> This method is needed because we have a custom title bar rather than the default Android title bar.
	 * See the theme definitons in styles.xml.
	 * 
	 * @param textViewId int
	 * @return void
	 */

	public void setTitleFromActivityLabel (int textViewId)
	{
	    TextView tv = (TextView) findViewById (textViewId);
	    if (tv != null) tv.setText (getTitle ());
	} // end setTitleText

	/**
	 * Show a string on the screen via Toast.
	 * 
	 * @param msg String
	 * @return void
	 */

	public void toast (String msg)
	{
	    Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_SHORT).show ();
	} // end toast

	/**
	 * Send a message to the debug log and display it using Toast.
	 */
	public void trace (String msg) 
	{
	    Log.d("HOMEOGRATUIT", msg);
	    toast (msg);
	} 
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 * declaration des menus qui apparait lorsque l'on fait OPTION sur le tel.
	 * implementer : Button QUITTER, SETTINGS
	 * reste a faire: faire apparaitre SETTINGS...
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(optionGroupId,optionAffectionsItemId, optionAffectionsOrder, getString(R.string.optionAffections));
		return super.onCreateOptionsMenu(menu);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 *
	 * declaration des actions du menu OPTION
	 * implementer : Button QUITTER
	 * reste a faire: SETTINGS... etc
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case optionAffectionsItemId:
			startActivity (new Intent(getApplicationContext(), AffectionsActivity.class));
	        break;
		}
		return super.onOptionsItemSelected(item);
	}
	
} // end class
